<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编程1练习</title>
    <style lang="css">
        #linkList > a {
            margin-right: 8px;
        }

        #linkList > a:last-child {
            margin-right: 0;
        }
    </style>
</head>
<body>
<div>
    <ul id="linkList">
    </ul>
</div>
<script>
    /**
     * router所用的数据源
     * @type {{mode: string, routes: [
     * {path: string, component: string},
     * {path: string, component: string},
     * {path: string, component: string}]}}
     */
    let totalHTML = '';

    let routerSource = {
        mode: 'hash',
        routes: [
            {
                path: '/index',
                name: '主页',
                component: '<div><h1>主页</h1><p>王诗阳的第一个主页</p></div>'
            }, {
                path: '/page1',
                name: '第一个页面',
                component: '<div><h1>第一个页面</h1><p>我的家在海洋<br>太阳给了我力量</p></div>'
            }, {
                path: '/page2',
                name: '第二个页面',
                component: '<div><h1>第二个页面</h1><p>力量大 本领强<br>打得妖魔无处藏</p></div>'
            }
        ]
    };

    applyRoutes(routerSource);

    function applyRoutes(rs) {
        let routes = rs.routes;
        let count = 1;
        routes.forEach(item => {
            let a = document.createElement('a');
            a.innerText = item.name;
            a.href = `${document.location.href}#${item.path}`;
            if (item.name === undefined) {
                a.innerText = `无标题${count}`;
            }
            a.onclick = () => {
                if (window.location.hash === '')
                    totalHTML = document.body.innerHTML;
            };
            document.querySelector('#linkList').appendChild(a);
        });
    }

    window.onpopstate = () => {
        console.log('后退或前进操作');
    };

    //浏览器的后退与前进操作
    window.onhashchange = () => {
        let singleHash = window.location.hash.replace(/#/g, '');
        if (singleHash === '') {
            document.body.innerHTML = totalHTML;
        } else {
            let routeInfo = routerSource.routes.filter(e => e.path.match(singleHash) !== null)[0];
            document.body.innerHTML = routeInfo.component;
        }
    }

</script>
</body>
</html>